<template>
  <!-- 标题 -->
  <p class="title">{{ pageData.title }}</p>

  <!-- 表格 -->
  <Table ref="tableRef" :search="search" :tools="tools" :columns="columns" :api="getRoleInfo" />

  <!-- 增加模态框 -->
  <n-modal v-model:show="pageData.isShowAddModel" :mask-closable="false" preset="dialog" title="增加" positive-text="确定"
    negative-text="取消" style="width: 700px" @positive-click="add" @negative-click="addCancel"
    @after-leave="closeAddModel">
    <Form :config="addFormConfig" ref="addFormRef" />


  </n-modal>

  <!-- 修改模态框 -->
  <n-modal v-model:show="pageData.isShowUpdateModel" :mask-closable="false" preset="dialog" title="编辑"
    positive-text="确定" negative-text="取消" style="width:650px" @positive-click="update" @negative-click="updateCancel"
    @after-leave="closeUpdateModel">
    <Form ref="updateFormRef" :config="updateFormConfig" />
  </n-modal>

  <n-modal v-model:show="pageData.isShowAssignModel" :mask-closable="false" preset="dialog" title="分配权限"
    positive-text="确定" negative-text="取消" style="width: 650px" @positive-click="assign" @negative-click="assignCancel"
    @after-leave="closeAssignModel">
    <Form ref="assignFormRef" :config="authFormConfig" />
  </n-modal>

</template>

<script setup lang="ts">
import { deleteRole, addUserRole, getRoleInfo, addRole, editRole, deleteRoleById, getAllAuth, getAuthByRoleId, deleteAuthById, addAuthById } from '@/api/system/user'
import { NButton, NSpace } from 'naive-ui';
import { h, reactive, ref } from 'vue';
import { addFormConfig, updateFormConfig, authFormConfig } from './config'
import { useRoute } from 'vue-router'
import uploadIcon from "@/assets/icons/upload.png";
import { deepClone } from '@/utils/lib/clone';
import getBASE64 from '@/utils/lib/upload'
import { formatDate } from '@/utils/lib/date';

export interface IDataSource {
  tools: Record<string, any>[]
  data: Record<string, any>[]
  columns: Record<string, any>[]
  loading: boolean
  pageData: Record<string, any>[]
}

const addFormRef = ref()
const updateFormRef = ref()
const assignFormRef = ref()


const tableRef = ref()



const route = useRoute()

const closeUpdateModel = () => {
  pageData.isShowUpdateModel = false
}

const closeAddModel = () => {
  pageData.isShowAddModel = false
}

const closeAssignModel = () => {
  pageData.isShowAssignModel = false
}



/**
 * 增加角色
 */
const add = async () => {
  try {
    const instance = addFormRef.value.getFormRef()
    console.log(instance.model);
    instance.validate(async (err) => {
      if (!err) {
        let data = deepClone(instance.model)
        data.role_id = parseInt(data.role_id)
        console.log(data);

        await addRole(data)
        tableRef.value.getData()
      } else {
        window['$message'].error('增加角色失败')
      }
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 更新角色
 */
const update = async () => {
  try {
    const instance = updateFormRef.value.getFormRef()
    // console.log(instance.model);
    instance.validate(async (err) => {
      if (!err) {
        let data = {
          ...instance.model,
        }
        console.log(data);

        await editRole(data)
        tableRef.value.getData()
      } else {
        window['$message'].error('更新角色失败')
      }
    })


  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 增加弹窗取消
 */
const addCancel = () => {
  pageData.isShowAddModel = false
}

/**
 * 分配弹窗取消
 */
const assignCancel = () => {
  pageData.isShowAssignModel = false
}


/**
 * 更新弹窗取消
 */
const updateCancel = () => {
  pageData.isShowUpdateModel = false
}

const addRoles = (val) => {
  console.log('add', val);
  pageData.isShowAddModel = true
}

const editRoles = (row) => {
  console.log('edit', row);
  pageData.selectedRow = deepClone(row)
  pageData.isShowUpdateModel = true
  updateFormConfig.formItems.forEach(item => {
    if (item.field === 'role_id') {
      item.value = row.role_id
    }
    if (item.field === 'role_name') {
      item.value = row.role_name
    }
    if (item.field === 'des') {
      item.value = row.des === '无' ? '' : row.des
    }
  })
}

/**
 * 删除角色
 */
const deleteRoles = async (row) => {
  try {
    console.log('delete', row);
    window['$dialog'].success({
      title: '删除',
      content: '是否删除该条数据？',
      maskClosable: false,
      negativeText: '取消',
      positiveText: '确定',
      onPositiveClick: async () => {
        await deleteRoleById({
          role_id: row.role_id
        })
        tableRef.value.getData()
      }
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 获取角色权限
 * @param user_id 角色id
 */
const getAuthById = async (role_id: number) => {
  try {
    const data = {
      role_id
    }
    const res = await getAuthByRoleId(data)
    if (res.data.code === 200) {
      pageData.isAuth = res.data.data.length > 0 ? true : false
      return Promise.resolve(res.data.data)
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

/**
 * 分配权限
 */
const assign = async () => {
  try {
    const instance: Record<string, any> = assignFormRef?.value?.getFormRef();
    console.log(instance.model);

    if (instance.model.auth.length === 0) {
      return
    }
    if (pageData.isAuth) {
      const res = await deleteAuthById({
        role_id: instance.model.role_id
      })
      if (res.data.code === 200) {
        await addAuthById({
          ...instance.model
        })
      }
    } else {
      await addAuthById({
        ...instance.model
      })
    }


  } catch (error) {
    return Promise.reject(error)
  }
}

const assignAuth = async (row) => {
  try {
    pageData.selectedRow = deepClone(row)
    const res = await getAuthById(pageData.selectedRow.role_id)
    pageData.isShowAssignModel = true
    authFormConfig.formItems.forEach(item => {
      if (item.field === 'role_id') {
        item.value = row.role_id
      }
      if (item.field === 'auth') {
        item.value = res.map(item => item.permission_id)
        item.options = pageData.auth.map(item => {
          return {
            label: item.permission_name,
            value: item.permission_id
          }
        })
      }
    })
    console.log('roleFormConfig.formItems', authFormConfig.formItems);
  } catch (error) {
    return Promise.reject(error)
  }

}

/**
 * 搜索栏
 */
const search = [

]

/**
 * 工具栏按钮
 */
const tools = [
  {
    name: ' 新增角色',
    type: 'error',
    handleClick: addRoles
  }
]

/**
 * 表格
 */
const columns = [
  {
    title: '角色名称',
    key: 'role_name',
    width: 200,
  },
  {
    title: '角色描述',
    key: 'des',
    width: 350,
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    render(row) {
      return h(NSpace, null, [
        h(NButton, {
          type: 'info',
          size: 'small',
          onClick: () => editRoles(row)
        }, () => '编辑'),
        h(NButton, {
          type: 'error',
          size: 'small',
          onClick: () => deleteRoles(row)
        }, () => '删除'),
        h(NButton, {
          type: 'primary',
          size: 'small',
          disabled:row.role_name === '超级管理员',
          onClick: () => assignAuth(row)
        }, () => '分配权限')
      ])
    }
  }
]


const pageData = reactive({
  selectedRow: {} as any,
  isShowAddModel: false as boolean,
  isShowUpdateModel: false as boolean,
  isShowAssignModel: false as boolean,
  title: route.meta.title as string,
  auth: [] as any,
  isAuth: false,   // 当前角色是否有权限
})

const getAuth = async () => {
  try {
    const res = await getAllAuth()
    if (res.data.code === 200) {
      pageData.auth = res.data.data
      console.log(pageData.auth);

    }
  } catch (error) {
    return Promise.reject(error)
  }
}
getAuth()






</script>

<style scoped lang="less">
@import '@/styles/mixin.less';

.title {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}

.upload-box {
  .flex(row, flex-start, center);

  .img-right-box {
    margin-left: 101px;
  }

  .img-box {
    .flex(row, flex-start, center);
    padding-left: 70px;

    .name {
      margin-right: 12px;

      span {
        color: #d03050;
      }
    }

    .img {
      // margin-top: 10px;
      margin-left: 10px;
      width: 100px;
      height: 100px;
      border: 2px dotted #ccc;
      background-color: rgb(250, 250, 252);
      .flex(row, center, center);
      cursor: pointer;

      p {
        font-size: 20px;
      }

      &:hover {
        border: 2px dotted green;
      }

      .icon-box {
        .flex(column, center, center);

        .icon-title {
          font-size: 14px;
          color: #666;
        }
      }
    }

    .file-input {
      display: none;
    }
  }
}
</style>